package cn.infozr.api.client;

import java.util.UUID;
import java.util.List;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.annotation.JsonInclude;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.TreeMap;

/**
 * 下属门店管理接口客户端
 * 用于测试 https://IP:端口/ygydapi/v1/editSubStore 接口
 */
public class SubStoreManagementApiClient extends BaseClient {
    
    /**
     * 下属门店管理请求参数类
     */
    public static class SubStoreManagementRequest {
        private String appId;
        private String timestamp;
        private String reqId;
        private String type;
        private String data;
        private String sign;
        
        // 构造函数
        public SubStoreManagementRequest() {
            this.timestamp = String.valueOf(System.currentTimeMillis());
            this.reqId = UUID.randomUUID().toString().replace("-", "");
        }
        
        // Getters and Setters
        public String getAppId() { return appId; }
        public void setAppId(String appId) { this.appId = appId; }
        
        public String getTimestamp() { return timestamp; }
        public void setTimestamp(String timestamp) { this.timestamp = timestamp; }
        
        public String getReqId() { return reqId; }
        public void setReqId(String reqId) { this.reqId = reqId; }
        
        public String getType() { return type; }
        public void setType(String type) { this.type = type; }
        
        public String getData() { return data; }
        public void setData(String data) { this.data = data; }
        
        public String getSign() { return sign; }
        public void setSign(String sign) { this.sign = sign; }
    }
    
    /**
     * 生成数据签名
     * @param request 请求参数对象
     * @return 签名字符串
     * @throws Exception 加密异常
     */
    protected String generateSign(SubStoreManagementRequest request) throws Exception {
        // 按照字段名的字典序拼接参数
        TreeMap<String, String> params = new TreeMap<>();
        params.put("appId", request.getAppId());
        params.put("reqId", request.getReqId());
        params.put("timestamp", request.getTimestamp());
        params.put("type", request.getType());
        params.put("data", request.getData());
        
        return cn.infozr.api.util.SM3SignatureUtil.generateSignature(params, SECRET_KEY);
    }
    
    /**
     * 调用下属门店管理接口
     * @param type 操作类型：1新增 2删除
     * @param data 门店统一社会信用代码列表
     * @return 接口响应结果
     * @throws Exception 网络或解析异常
     */
    public String manageSubStore(String type, List<String> data) throws Exception {
        // 构造请求参数
        SubStoreManagementRequest request = new SubStoreManagementRequest();
        request.setAppId(APP_ID);
        request.setTimestamp(String.valueOf(System.currentTimeMillis()));
        request.setType(type);
        
        // 将门店统一社会信用代码列表转换为逗号分隔的字符串
        if (data != null && !data.isEmpty()) {
            StringBuilder dataBuilder = new StringBuilder();
            for (int i = 0; i < data.size(); i++) {
                if (i > 0) {
                    dataBuilder.append(",");
                }
                dataBuilder.append(data.get(i));
            }
            request.setData(dataBuilder.toString());
        }
        
        // 生成签名
        request.setSign(generateSign(request));
        
        // 发送POST请求
        return sendPostRequest(SUB_STORE_API_URL, request);
    }
    
    /**
     * 发送POST请求
     * @param url 请求地址
     * @param request 请求参数对象
     * @return 响应结果
     * @throws Exception 网络异常
     */
    protected String sendPostRequest(String url, SubStoreManagementRequest request) throws Exception {
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // 设置请求方法和请求头
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json; utf-8");
        con.setRequestProperty("Accept", "application/json");
        con.setDoOutput(true);

        // 序列化请求参数，过滤空值
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        String jsonInputString = objectMapper.writeValueAsString(request);
        System.out.println("请求参数: " + jsonInputString);
        
        // 发送请求
        try(OutputStream os = con.getOutputStream()) {
            byte[] input = jsonInputString.getBytes("utf-8");
            os.write(input, 0, input.length);
        }

        int responseCode = con.getResponseCode();
        // 读取响应
        if (responseCode == HttpURLConnection.HTTP_OK) {
            try(BufferedReader br = new BufferedReader(
                    new InputStreamReader(con.getInputStream(), "utf-8"))) {
                StringBuilder response = new StringBuilder();
                String responseLine = null;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                return response.toString();
            }
        } else {
            // 读取错误响应
            try(BufferedReader br = new BufferedReader(
                    new InputStreamReader(con.getErrorStream(), "utf-8"))) {
                StringBuilder response = new StringBuilder();
                String responseLine = null;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                System.err.println("错误响应: " + response.toString());
                return "{\"code\":" + responseCode + ",\"msg\":\"请求失败\"}";
            }
        }
    }
    
    /**
     * 解析并打印管理结果
     * @param jsonResponse JSON响应字符串
     * @throws Exception 解析异常
     */
    public void parseAndPrintManageResult(String jsonResponse) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        com.fasterxml.jackson.databind.JsonNode rootNode = objectMapper.readTree(jsonResponse);
        
        System.out.println("接口响应:");
        System.out.println("状态码: " + (rootNode.has("code") ? rootNode.get("code").asText() : "无"));
        System.out.println("消息提示: " + (rootNode.has("msg") ? rootNode.get("msg").asText() : "无"));
        System.out.println("请求ID: " + (rootNode.has("reqId") ? rootNode.get("reqId").asText() : "无"));
        System.out.println("数据体: " + (rootNode.has("data") ? rootNode.get("data").toString() : "无"));
    }
    
    /**
     * 主方法 - 测试接口调用
     */
    public static void main(String[] args) {
        try {
            SubStoreManagementApiClient client = new SubStoreManagementApiClient();
            
            // 构造测试数据 - 新增门店
            java.util.List<String> storeCodes = new java.util.ArrayList<>();
            storeCodes.add("91340100774951109T");
//            storeCodes.add("913401007608485413");
//            storeCodes.add("913401007608485414");

            System.out.println("正在新增门店信息...");
            String result = client.manageSubStore("1", storeCodes);

            // 解析并打印结果
            client.parseAndPrintManageResult(result);

            System.out.println("\n------------------\n");
            
            // 构造测试数据 - 删除门店
//            java.util.List<String> deleteStoreCodes = new java.util.ArrayList<>();
//            deleteStoreCodes.add("91340100774951109T");
//
//            System.out.println("正在删除门店信息...");
//            String deleteResult = client.manageSubStore("2", deleteStoreCodes);
//
////             解析并打印结果
//            client.parseAndPrintManageResult(deleteResult);
            
        } catch (Exception e) {
            System.err.println("门店管理操作时发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }
}